package salesdata

import (
	"strconv"

	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"

	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/until"
)

type (
	salesdata struct {
		ID                bson.ObjectId `json:"_id" bson:"_id"`
		Ordernumber       string        `json:"ordernumber" bson:"ordernumber"`
		OnlineOrderNumber string        `json:"onlineordernumber" bson:"onlineordernumber"`
		PayDate           int64         `json:"paydate" bson:"paydate"`
		ShipDate          int64         `json:"shipdate" bson:"shipdate"`
		PackageNumber     string        `json:"packagenumber" bson:"packagenumber"`
		ShipUser          string        `json:"shipuser" bson:"shipuser"`
		City              string        `json:"city" bson:"city"`
		District          string        `json:"district" bson:"district"`
		Address           string        `json:"address" bson:"address"`
		LargeNumber       string        `json:"largenumber" bson:"largenumber"`
		Sku               string        `json:"sku" bson:"sku"`
		CargoName         string        `json:"cargoname" bson:"cargoname"`
		Size              string        `json:"size" bson:"size"`
		Color             string        `json:"color" bson:"color"`
		Count             string        `json:"count" bson:"count"`
		Price             string        `json:"price" bson:"price"`
		Amount            string        `json:"amount" bson:"amount"`
		Cost              string        `json:"cost" bson:"cost"`
	}
	insertsalesdata struct {
		Ordernumber       string `json:"ordernumber" bson:"ordernumber"`
		OnlineOrderNumber string `json:"onlineordernumber" bson:"onlineordernumber"`
		PayDate           int64  `json:"paydate" bson:"paydate"`
		ShipDate          int64  `json:"shipdate" bson:"shipdate"`
		PackageNumber     string `json:"packagenumber" bson:"packagenumber"`
		ShipUser          string `json:"shipuser" bson:"shipuser"`
		City              string `json:"city" bson:"city"`
		District          string `json:"district" bson:"district"`
		Address           string `json:"address" bson:"address"`
		LargeNumber       string `json:"largenumber" bson:"largenumber"`
		Sku               string `json:"sku" bson:"sku"`
		CargoName         string `json:"cargoname" bson:"cargoname"`
		Size              string `json:"size" bson:"size"`
		Color             string `json:"color" bson:"color"`
		Count             string `json:"count" bson:"count"`
		Price             string `json:"price" bson:"price"`
		Amount            string `json:"amount" bson:"amount"`
		Cost              string `json:"cost" bson:"cost"`
	}
	Size struct {
		S   int `json:"S"`
		M   int `json:"M"`
		L   int `json:"L"`
		XL  int `json:"XL"`
		XXL int `json:"XXL"`
	}
	Color struct {
		Value int  `json:"value"`
		Size  Size `json:"size"`
	}
)

type OXYSalesData struct{}

func NewOXYSalesData() *OXYSalesData {
	salesData := &OXYSalesData{}
	return salesData
}

func (sd *OXYSalesData) GetSalesDataListHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	resultsType := c.QueryParam("type")
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sales_data"
	query, count, err := model.DB().Query(M, currentpage, perpage)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []salesdata{}
	query.All(&ps)
	results := make(map[string]Color)
	if resultsType == "largenumber" {
		for _, item := range ps {
			sizecount, _ := strconv.Atoi(item.Count)
			_, ok := results[item.Color]
			if !ok {
				results[item.Color] = Color{
					Value: 0,
					Size: Size{
						S:   0,
						M:   0,
						L:   0,
						XL:  0,
						XXL: 0,
					},
				}
			}
			temp := results[item.Color]
			switch item.Size {
			case "S":
				temp.Size.S += sizecount
				break
			case "M":
				temp.Size.M += sizecount
				break
			case "L":
				temp.Size.L += sizecount
				break
			case "XL":
				temp.Size.XL += sizecount
				break
			case "XXL":
				temp.Size.XXL += sizecount
				break

			default:
				break

			}
			temp.Value += sizecount
			results[item.Color] = temp
		}
		c.JSON(200, map[string]interface{}{
			"msg":   "success",
			"data":  results,
			"count": count,
		})
	} else {
		c.JSON(200, map[string]interface{}{
			"msg":   "success",
			"data":  ps,
			"count": count,
		})
	}
	return nil
}

func (sd *OXYSalesData) AddSalesDataHandler(c echo.Context) error {
	saleslist := []insertsalesdata{}
	if err := c.Bind(&saleslist); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sales_data"

	errInfo := []error{}
	for _, item := range saleslist {
		err := model.DB().Insert(item)
		if err != nil {
			log.Error("插入失败", err)
			errInfo = append(errInfo, err)

		}
	}
	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"info": errInfo,
	})

	// var data []interface{}
	// for _,item := range saleslist{
	// 	data = append(data, item)
	// }
	// err := model.DB().InsertAll(data...)
	// if err != nil {
	// 	log.Error("插入数据失败",err)
	// }
	// c.JSON(200, map[string]interface{}{
	// 	"msg":   "success",
	// 	"info": err,
	// })

	return nil
}
func (sd *OXYSalesData) GetSalesLargeNumberListHandler(c echo.Context) error {
	jsonquery := c.QueryParam("like")
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sales_data"
	query, _, err := model.DB().Query(M, 0, 0)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []salesdata{}
	query.All(&ps)
	largenumberList := make([]string, 0)
	for _, item := range ps {
		largenumberList = append(largenumberList, item.LargeNumber)
	}
	largenumberList = until.RemoveRepByMap(largenumberList)
	// str, err := json.Marshal(ps)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"data": largenumberList,
		// "count":count,
	})

	return nil
}
func (sd *OXYSalesData) GetSalesSkuListHandler(c echo.Context) error {
	jsonquery := c.QueryParam("like")
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sales_data"
	query, _, err := model.DB().Query(M, 0, 0)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []salesdata{}
	skuList := []salesdata{}
	query.All(&ps)
	// skuList :=make([]string,0)
	tempMap := map[string]byte{} // 存放不重复主键
	for _, item := range ps {
		l := len(tempMap)
		tempMap[item.Sku] = 0
		if len(tempMap) != l { // 加入map后，map长度变化，则元素不重复
			skuList = append(skuList, item)
		}
	}
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"data": skuList,
		// "count":count,
	})

	return nil
}

func (sd *OXYSalesData) GetCombineSalesDataListHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "combine_data"
	query, count, err := model.DB().Query(nil, currentpage, perpage)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []salesdata{}
	query.All(&ps)

	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  ps,
		"count": count,
	})

	return nil
}

func (sd *OXYSalesData) AddCombineSalesDataHandler(c echo.Context) error {
	saleslist := []insertsalesdata{}
	if err := c.Bind(&saleslist); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "combine_data"
	var data []interface{}
	for _, item := range saleslist {
		data = append(data, item)
	}
	err := model.DB().InsertAll(data...)
	if err != nil {
		log.Error("插入数据失败", err)
	}
	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"info": err,
	})

	return nil
}

func (sd *OXYSalesData) DelCombineSalesData(c echo.Context) error {
	collectionName := c.QueryParam("collectionName")
	log.Info("DelCombineSalesData-collectionName:", collectionName)
	model.DB().Dbname = "OxyCms"
	model.DB().Document = collectionName
	err := model.DB().DropCollection()
	if err != nil {
		log.Error("删除出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
